import {
  Injectable,
  CanActivate,
  ExecutionContext,
  ForbiddenException,
  Inject,
  forwardRef,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthService } from '../../auth/auth.service';
import { PERMISSION_KEY } from '../decorators/permission.decorator';

@Injectable()
export class PermissionGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    @Inject(forwardRef(() => AuthService))
    private authService: AuthService,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const requiredPermissions = this.reflector.getAllAndOverride<string[]>(
      PERMISSION_KEY,
      [context.getHandler(), context.getClass()],
    );

    console.log('🔍 PermissionGuard - Required permissions:', requiredPermissions);

    if (!requiredPermissions) {
      console.log('✅ PermissionGuard - No permissions required, allowing access');
      return true;
    }

    const request = context.switchToHttp().getRequest();
    const user = request.user;

    console.log('👤 PermissionGuard - Current user:', { userId: user?.sub, username: user?.username });

    if (!user) {
      console.log('❌ PermissionGuard - No user found in request');
      throw new ForbiddenException('用户未认证');
    }

    try {
      const userPermissions = await this.authService.getUserPermissions(user.sub);
      
      console.log('🔑 PermissionGuard - User permissions:', userPermissions);
      console.log('🔄 PermissionGuard - Checking required vs user permissions:');
      console.log('   Required:', requiredPermissions);
      console.log('   User has:', userPermissions);
      
      const hasPermission = requiredPermissions.some(permission => {
        const has = userPermissions.includes(permission);
        console.log(`   ${permission}: ${has ? '✅' : '❌'}`);
        return has;
      });

      console.log('🎯 PermissionGuard - Final result:', hasPermission ? 'ALLOWED' : 'DENIED');

      if (!hasPermission) {
        console.log('❌ PermissionGuard - Access denied - insufficient permissions');
        throw new ForbiddenException('权限不足');
      }

      console.log('✅ PermissionGuard - Access granted');
      return true;
    } catch (error) {
      console.log('💥 PermissionGuard - Error occurred:', error.message);
      if (error instanceof ForbiddenException) {
        throw error;
      }
      throw new ForbiddenException('权限验证失败');
    }
  }
}